package org.dentalcard.ui.security.tools;

import org.dentalcard.entity.DecUser;
import org.dentalcard.entity.Shift;
import org.dentalcard.service.impl.DecUserDaoImpl;
import org.dentalcard.ui.api.tools.AbstractDecTableModel;

import java.util.ArrayList;
import java.util.List;

/**
 * @user: Vladimir Chernishov
 * @date: 21.12.11
 * @time: 12:13
 */
public class UserTableModel extends AbstractDecTableModel {

    private List<DecUser> users;
    private List<ButtonsPanel> buttons;
    
    public UserTableModel() {
        super(new String[]{"Usename", "Password", "Role", ""});
        reload();
    }

    public void reload() {
        users = new DecUserDaoImpl().getUsers();
        buttons = new ArrayList<ButtonsPanel>(users.size() + 1);
        for(int i = 0; i < users.size(); i++){
            buttons.add(new ButtonsPanel(users.get(i), this));
        }
        fireTableDataChanged();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        DecUser user = users.get(rowIndex);
        switch (columnIndex) {
            case 0 :{
                return user.getName();
            }
            case 1 :{
                return user.getPassword();
            }
            case 2 :{
                return user.getId();
            }
            case 3:{
                return buttons.get(rowIndex);
            }
        }
        return "";

    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        DecUser user = users.get(rowIndex);
        switch (columnIndex) {
            case 0 :{
                user.setName(aValue.toString());
                break;
            }
            case 1 :{
                user.setPassword(aValue.toString());
                break;
            }
            case 2 :{
                user.getId();
                break;
            }
        }
        if(columnIndex != 3){
            buttons.get(rowIndex).setChanged();
        }
        fireTableCellUpdated(rowIndex, columnIndex);
        fireTableCellUpdated(rowIndex, 3);
    }

    @Override
    public int getRowCount() {
        return users.size();
    }
}
